<template>
  <div id="log-window">
    <div id="title">
      <h2>实时日志</h2>
      <button v-if="isRunning" @click="stop">stop</button>
      <button v-else @click="start">start</button>
    </div>
    <rolling-view id="log" :cache="cache" :status="status" :capacity="200" />
  </div>
</template>

<script>
import { closeWebSocket, connectWebSocket, sendMessage } from '@/utils/scoket'
import RollingLog from './rolling.vue.vue'
export default {
  name: 'App',
  components: {
    'rolling-view': RollingLog
  },
  data() {
    return {
      cache: [],
      status: 'idle'
    }
  },
  computed: {
    isRunning() {
      return this.status === 'running'
    }
  },
  mounted() {
    // 添加监听事件
    window.addEventListener('beforeunload', e => this.closeWebSocket())
  },

  methods: {
    getRandomItem(list) {
      return list[this.getRandomInt(list.length)]
    },
    getRandomInt(range) {
      return Math.floor(Math.random() * range)
    },
    stop() {
      this.status = 'idle'
      closeWebSocket()
      this.socketOpen = false
    },
    start() {
      this.subscribeSocket()
      this.status = 'running'
    },
    /**
     * @description 订阅socket消息
     */
    async subscribeSocket() {
      if (!this.socketOpen) {
        await connectWebSocket(9200, 'log', this.socketMsgHandler, this.socketError)
        this.socketOpen = true
      }
      const params = { type: 'WS_LOG' }
      sendMessage(JSON.stringify(params))
    },
    socketError() {
      closeWebSocket()
      this.socketOpen = false
    },
    /**
     * @description 处理socket消息
     * @param {string} msg socket消息体
     */
    socketMsgHandler(msg) {
      const { type, data } = JSON.parse(msg)
      if (type === 'WS_LOG') {
        const logs = []
        logs.push(data);
        [].push.apply(this.cache, logs)
      }
    }
  }
}
</script>

<style>
#log-window {
  height: 820px;
  margin: 0;
  padding: 16px 16px;
  box-sizing: border-box;
}

#title {
  height: 48px;
}
#title h2 {
  float: left;
  margin: 0;
}
#title::after {
  clear: both;
  content: '';
  display: block;
}
#title button {
  float: right;
  font-size: 20px;
  cursor: pointer;
  border-radius: 4px;
  background-color: white;
  border: 1px solid #999;
  padding: 5px 20px;
}
#title button:hover {
  background-color: #ddd;
}
#title button:focus {
  outline: none;
}
</style>
